import 'package:app_core/app_core.dart';

/// HTTP请求方式
enum HttpMethod { get, post, put, delete, patch, head }

///转为"GET","POST"
extension HttpMethodExt on HttpMethod {
  String get dioMethod => toString().split('.').last.toUpperCase();
}

/// API统一接口 ，所有API必须实现的两个属性：
abstract class BaseApi {
  String get path;
  HttpMethod get method;
}

/// 通用泛型扩展，所有实现BaseApi的枚举都自动拥有request<T>()
/// 为Api添加功能，<Api extends BaseApi>: Api 必须实现 BaseApi 接口
extension ApiRequestExt<Api extends BaseApi> on Api {
  /// 基础请求方法，仅供内部使用
  @Deprecated('UI层请使用 request() 方法替代，此方法仅供Api内部使用')
  Future<ApiResponse<T>> httpRequest<T>({
    Map<String, dynamic>? params,
    // dynamic data,
    T Function(Map<String, dynamic>)? fromJson,
    RequestConfig? config,
    Function(int code, String? msg)? onErrorCode,
  }) {
    switch (method) {
      case HttpMethod.get:
      case HttpMethod.delete:

        /// GET/DELETE：所有参数作为URL查询参数
        return DioManager.request<T>(path: path, method: method.dioMethod, params: params, fromJson: fromJson, config: config, onErrorCode: onErrorCode);

      case HttpMethod.post:
      case HttpMethod.put:
      case HttpMethod.patch:

        /// POST/PUT/PATCH：所有参数作为请求体
        return DioManager.request<T>(path: path, method: method.dioMethod, data: params, fromJson: fromJson, config: config, onErrorCode: onErrorCode);
      case HttpMethod.head:
        // TODO: Handle this case.
        throw UnimplementedError();
    }
  }
}

///单个请求配置类
class RequestConfig {
  final Map<String, String>? headers;
  final bool autoToken;
  final Duration? timeout;

  /// 可选的单请求 baseUrl，若提供则覆盖全局 baseUrl
  final String? baseUrl;

  const RequestConfig({this.headers, this.autoToken = true, this.timeout, this.baseUrl});
}
